import { ComponentRef,Injectable, ComponentFactoryResolver, Injector, ApplicationRef } from '@angular/core';


export  class DocumentWrapper extends Document {
    
}
export  class WindowWrapper extends Window {

}

@Injectable({
    providedIn: 'root'
})
export  class ExDynamicService {
    private document:any;
    private factory:any;
    private injector:any;
    private appRef:any;
    constructor(document: DocumentWrapper, factory: ComponentFactoryResolver, injector: Injector, appRef: ApplicationRef){
        this.document = document;
        this.factory = factory;
        this.injector = injector;
        this.appRef = appRef;
    };


    generator(Container:any) {
        var /** @type {?} */ id = this.makeID();
        var /** @type {?} */ component = this.factory
            .resolveComponentFactory(Container)
            .create(this.injector);
        this.appRef.attachView(component.hostView);
        var /** @type {?} */ hostElement = this.document.createElement('div');
        hostElement.setAttribute('id', id);
        component.instance.id = id;
        hostElement.appendChild(((component.hostView)).rootNodes[0]);
        this.document.body.appendChild(hostElement);
        return component;
    }


    destroy(com:any) {
        var _this = this;
        var /** @type {?} */ timer = setTimeout(function () {
            _this.destroyWait(com);
            clearTimeout(timer);
        }, 500);
    }


    destroyWait(com:any) {
        var /** @type {?} */ id = com.instance.id;
        this.appRef.detachView(com.hostView);
        com.destroy();
        try {
            var /** @type {?} */ hostElement = this.document.getElementById(id);
            hostElement && hostElement.parentElement.removeChild(hostElement);
        }
        catch (err) { }
    }

    makeID() {
        return Math.random().toString(16).substr(2, 8);
    }
}


